package com.gis.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gis.bean.Message;
import com.gis.dao.MessageDao;
import com.gis.dao.UserDao;
import com.gis.util.Constant;
import com.gis.util.ResponseUtil;
import com.gis.util.RestResponse;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;

@WebServlet("/resetPassword")
public class ResetPasswordServlet extends HttpServlet {
	MessageDao messageDao = new MessageDao();
	UserDao userDao = new UserDao();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String newPassword = req.getParameter("newPassword");
		String randomCode = req.getParameter("randomCode");
		
		Message message = messageDao.selectByUsername(username);
		if(message == null) {
			ResponseUtil.writeJson(resp, RestResponse.fail(Constant.USER_NOT_EXIST));
			return;
		}
		
		if(!message.getRandomCode().equals(randomCode)) {
			ResponseUtil.writeJson(resp, RestResponse.fail(Constant.LINK_INVALID));
			return;
		}

		if(!DateUtil.isIn(new Date(), message.getSendTime(), DateUtil.offset(message.getSendTime(), DateField.DAY_OF_MONTH, 2))) {
			ResponseUtil.writeJson(resp, RestResponse.fail(Constant.LINK_INVALID));
			return;
		}
		// 验证都通过后修改密码
		int i = userDao.editPassword(username, newPassword);
		if (i<1) {
			ResponseUtil.writeJson(resp, RestResponse.fail(Constant.UPDATE_FAILED));
			return;
		}
		ResponseUtil.writeJson(resp, RestResponse.success(Constant.UPDATE_SUCCESS));
		return;
	}

}
